import { ref, onMounted, h } from "vue";
import dayjs from "dayjs";
import { usePublicHooks } from "@/views/system/hooks";
import { message } from "@/utils/message";
import { type FormItemProps } from "./types";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form.vue";
import { saveWeiXinCon, delWeiXinConfig, getWeiXinConfig } from "@/api/system";
import { ElMessageBox } from "element-plus";
export function weiXinConfig() {
  const switchLoadMap = ref({});
  const dataList = ref([]);
  const loading = ref(false);
  const formRef = ref();

  const { switchStyle } = usePublicHooks();
  const columns: TableColumnList = [
    {
      label: "编号",
      prop: "id",
      minWidth: 100,
      sortable: "custom"
    },
    {
      label: "配置名称",
      prop: "configName",
      minWidth: 120,
      sortable: "custom"
    },
    {
      label: "机构代码",
      prop: "comID"
    },
    {
      label: "授权域名",
      prop: "redirectUri",
      minWidth: 150
    },
    {
      label: "授权范围",
      prop: "scop",
      minWidth: 150
    },
    {
      label: "状态",
      minWidth: 130,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.disate}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 150
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "addTime",
      formatter: ({ addTime }) => dayjs(addTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const Result = await getWeiXinConfig();
    dataList.value = Result.result;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.disate === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.configName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );

          const Result = await saveWeiXinCon(row);
          if (Result.isSuccess) {
            message("已成功修改用户状态", {
              type: "success"
            });
          } else {
            message(Result.msg, { type: "error" });
          }
        }, 300);
      })
      .catch(() => {
        row.disate === 0 ? (row.disate = 1) : (row.disate = 0);
      });
  }

  async function handleDelete(row) {
    const Result = await delWeiXinConfig({ id: row.id });
    if (Result.isSuccess) {
      message(`已删除角色名称为 ${row.roleName} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  onMounted(() => {
    onSearch();
  });

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}配置`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          configName: row?.configName ?? "",
          appid: row?.appid ?? "",
          appSecret: row?.appSecret ?? "",
          redirectUri: row?.redirectUri ?? "",
          fileUploadAddress: row?.fileUploadAddress ?? "",
          authField: row?.authField ?? "",
          authTableName: row?.anthTableName ?? "",
          remark: row?.remark ?? "",
          disate: row?.disate ?? 1,
          scop: row?.scop ?? "",
          loginUrl: row?.loginUrl ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了配置名称为${curData.configName}的这条数据`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log(curData);
            const subResult = await saveWeiXinCon(curData);

            if (subResult.isSuccess) {
              chores();
            } else {
              message(subResult.msg, { type: "error" });
            }
          }
        });
      }
    });
  }

  const getConfigList = () => {
    console.log("this is a fnuntong");
  };

  return {
    getConfigList,
    columns,
    dataList,
    onSearch,
    loading,
    openDialog,
    handleDelete
  };
}
